﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OtpNet;
using NotifyAppBase;

namespace MyOTP
{

    public class AuthInfoViewModel : ObservableObject
    {

        public AuthInfoModel UserInfo { get; set; } = new AuthInfoModel();

        private string _UserRealName;

        public string UserRealName { get => _UserRealName; set => Set(ref _UserRealName, value); }


        private string _TagName;

        public string TagName { get => _TagName; set => Set(ref _TagName, value); }

        private string _OTPKey;

        public string OTPKey { get => _OTPKey; set => Set(ref _OTPKey, value); }


        private string _LastCode;

        public string LastCode { get => _LastCode; set => Set(ref _LastCode, value); }


        private string _Code;

        public string Code { get => _Code; set => Set(ref _Code, value); }


        private int _RemainingSeconds;

        public int RemainingSeconds { get => _RemainingSeconds; set => Set(ref _RemainingSeconds, value); }

        private string _UserName;

        public string UserName { get => _UserName; set => Set(ref _UserName, value); }


        private string _Password;

        public string Password { get => _Password; set => Set(ref _Password, value); }


        public Totp OtpObj { get; set; }


        public void UpdateCode()
        {
            if (string.IsNullOrEmpty(this.OTPKey))
            {
                return;
            }

            if (OtpObj == null)
            {
                OtpObj = AuthenticationService.GenerateOTP(this.OTPKey);
            }
            this.RemainingSeconds = OtpObj.RemainingSeconds();

            if (string.IsNullOrEmpty(this.Code))
            {
                this.Code = OtpObj.ComputeTotp();
            }

            if (this.RemainingSeconds <= 1)
            {
                string newCode = OtpObj.ComputeTotp();
                this.LastCode = this.Code;
                this.Code = newCode;
            }

        }
    }


    public class AuthInfoModel
    {
        public string UserRealName { get; set; }
        public string TagName { get; set; }
        public string OTPKey { get; set; }

        //方便复制
        public string UserName { get; set; }
        public string Password { get; set; }
    }

    public class AuthenticationService
    {

        // 生成6位验证码
        public static Totp GenerateOTP(string secretKey)
        {
            var totp = new Totp(Base32Encoding.ToBytes(secretKey));
            return totp;
        }
    }

}
